from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from decimal import Decimal
from goods.models import SKU
from meiduo_mall.utils.my_loginrequired import MyLoginRequiredMixin

#1, 订单结算
class OrderSettlementView(MyLoginRequiredMixin):
    def get(self, request):

        # 1,查询用户地址
        addresses = request.user.addresses.filter(is_deleted=False).all()

        # 2,获取redis中选中商品
        user = request.user
        redis_conn = get_redis_connection("carts")
        cart_dict = redis_conn.hgetall("carts_%s" % user.id)
        selected_list = redis_conn.smembers("selected_%s" % user.id)

        # 3,数据拼接
        sku_list = []
        total_count = 0  # 总数量
        total_amount = Decimal(0.0)  # 总金额
        for sku_id in selected_list:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id": sku.id,
                "default_image_url": sku.default_image_url.url,
                "name": sku.name,
                "price": str(sku.price),
                "count": int(cart_dict[sku_id]),
                "amount": str(int(cart_dict[sku_id]) * sku.price)
            }
            sku_list.append(sku_dict)


            #累加总数量,总金额
            total_count += int(cart_dict[sku_id])
            total_amount += (int(cart_dict[sku_id]) * sku.price)

        #4,运费, 实付款
        freight = Decimal(10.0)
        payment_amount = total_amount + freight




        # 携带数据,渲染页面
        context = {
            "addresses": addresses,
            "total_count": total_count,
            "total_amount": total_amount,
            "freight": str(freight),
            "payment_amount": str(payment_amount),
        }
        return render(request, 'place_order.html', context=context)
